package cn.edu.zut.hhr.handler;

import cn.edu.zut.hhr.utils.CheckUtil;
import cn.edu.zut.hhr.utils.RedisUtil;
import cn.edu.zut.hhr.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class TokenLogoutHandler implements LogoutHandler {

    RedisUtil redisUtil;

    public TokenLogoutHandler(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        String token = httpServletRequest.getHeader("token");
        CheckUtil.notNull(token,"不存在该用户");
        String username = TokenUtil.getUserInfoFromToken(token);
        redisUtil.del(username);
        HttpSession session = httpServletRequest.getSession();
        session.removeAttribute("userid");
        session.removeAttribute("username");
    }
}
